from django.contrib import admin
from .models import Server, Task, TaskLog, SystemLog
from import_export.admin import ImportExportModelAdmin

@admin.register(Server)
class ServerAdmin(ImportExportModelAdmin):
    list_display = ('name', 'hostname', 'port', 'username', 'created_at', 'created_by')
    search_fields = ('name', 'hostname', 'username')
    list_filter = ('created_at', 'created_by')
    readonly_fields = ('created_at', 'updated_at', 'created_by')
    
    def save_model(self, request, obj, form, change):
        if not change:  # 新增记录
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(Task)
class TaskAdmin(ImportExportModelAdmin):
    list_display = ('name', 'server', 'status', 'created_at', 'last_run_time', 'created_by', 'is_enabled')
    search_fields = ('name', 'description', 'command')
    list_filter = ('status', 'created_at', 'server', 'is_enabled')
    readonly_fields = ('created_at', 'updated_at', 'created_by', 'last_run_time')
    
    def save_model(self, request, obj, form, change):
        if not change:  # 新增记录
            obj.created_by = request.user
        super().save_model(request, obj, form, change)


@admin.register(TaskLog)
class TaskLogAdmin(ImportExportModelAdmin):
    list_display = ('task', 'status', 'started_at', 'completed_at', 'duration', 'started_by')
    search_fields = ('task__name', 'output', 'error')
    list_filter = ('status', 'started_at', 'task__server', 'started_by')
    readonly_fields = ('id', 'started_at', 'completed_at', 'started_by')
    fieldsets = (
        ('基本信息', {
            'fields': ('task', 'status', 'started_by', 'started_at', 'completed_at', 'duration')
        }),
        ('输出信息', {
            'fields': ('output', 'error')
        }),
    )
    
    def has_add_permission(self, request):
        return False  # 不允许手动添加日志


@admin.register(SystemLog)
class SystemLogAdmin(ImportExportModelAdmin):
    list_display = ('level', 'message', 'user', 'ip_address', 'created_at')
    search_fields = ('message', 'user__username', 'ip_address')
    list_filter = ('level', 'created_at', 'user')
    readonly_fields = ('id', 'created_at')
    
    def has_add_permission(self, request):
        return False  # 不允许手动添加日志
    
    def has_change_permission(self, request, obj=None):
        return False  # 不允许修改日志
    
    def has_delete_permission(self, request, obj=None):
        return request.user.is_superuser  # 只有超级用户可以删除日志
